package com.ec.pf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ec.api.client.UserClient;
import com.ec.pf.pojo.BindingInfo;
import com.ec.pf.pojo.FamilyElderlyBinding;
import com.ec.pf.service.FamilyElderlyBindingService;
import com.ec.common.domain.Result;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/binding")
@RequiredArgsConstructor
public class FamilyElderlyBindingController {
    private final FamilyElderlyBindingService familyElderlyBindingService;
    private final UserClient userClient;


    // 家属申请绑定老人
    @PostMapping("/family-to-elderly")
    public Result<FamilyElderlyBinding> bindFamilyToElderly(@RequestBody FamilyElderlyBinding request) {
        // 验证用户是否存在及角色
        Result<Long> familyRoleResult = userClient.getUserRoleId(request.getFamilyUserId());
        if (familyRoleResult.getData() == null || familyRoleResult.getData() != 3L) {
            return Result.error("家属用户ID无效或角色不正确");
        }
        Result<Long> elderlyRoleResult = userClient.getUserRoleId(request.getElderlyUserId());
        if (elderlyRoleResult.getData() == null || elderlyRoleResult.getData() != 2L) {
            return Result.error("老人用户ID无效或角色不正确");
        }
        try {
            FamilyElderlyBinding result = familyElderlyBindingService.bindFamilyToElderly(request.getFamilyUserId(), request.getElderlyUserId());
            return Result.ok(result);
        } catch (Exception e) {
            return Result.error("申请绑定失败：" + e.getMessage());
        }
    }

    // 老人申请绑定家属
    @PostMapping("/elderly-to-family")
    public Result<FamilyElderlyBinding> bindElderlyToFamily(@RequestBody FamilyElderlyBinding request) {
        // 验证用户是否存在及角色
        Result<Long> familyRoleResult = userClient.getUserRoleId(request.getFamilyUserId());
        if (familyRoleResult.getData() == null || familyRoleResult.getData() != 3L) {
            return Result.error("家属用户ID无效或角色不正确");
        }
        Result<Long> elderlyRoleResult = userClient.getUserRoleId(request.getElderlyUserId());
        if (elderlyRoleResult.getData() == null || elderlyRoleResult.getData() != 2L) {
            return Result.error("老人用户ID无效或角色不正确");
        }
        try {
            FamilyElderlyBinding result = familyElderlyBindingService.bindElderlyToFamily(request.getFamilyUserId(), request.getElderlyUserId());
            return Result.ok(result);
        } catch (Exception e) {
            return Result.error("申请绑定失败：" + e.getMessage());
        }
    }

    // 批准绑定申请
    @PutMapping("/{bindingId}/approve")
    public Result<Void> approveBinding(@PathVariable Long bindingId, @RequestBody FamilyElderlyBinding request) {
        try {
            boolean success = familyElderlyBindingService.approveBinding(bindingId, request.getApprovedByAdminId());
            return success ? Result.ok() : Result.error("批准绑定失败");
        } catch (Exception e) {
            return Result.error("批准绑定失败：" + e.getMessage());
        }
    }

    // 拒绝绑定申请
    @PutMapping("/{bindingId}/reject")
    public Result<Void> rejectBinding(@PathVariable Long bindingId) {
        try {
            boolean success = familyElderlyBindingService.rejectBinding(bindingId);
            return success ? Result.ok() : Result.error("拒绝绑定失败");
        } catch (Exception e) {
            return Result.error("拒绝绑定失败：" + e.getMessage());
        }
    }

    // 管理员模糊查询绑定关系
    @GetMapping
    public Result<Page<BindingInfo>> getBindingWithDetails(@RequestParam String familyName,
                                                           @RequestParam String elderlyName,
                                                           @RequestParam int page,
                                                           @RequestParam int size) {
        try {
            Page<BindingInfo> bindingInfoPage = familyElderlyBindingService.getBindingByFamilyAndElderlyNames(
                    familyName, elderlyName, page, size);
            return Result.ok(bindingInfoPage);
        } catch (Exception e) {
            return Result.error("查询绑定关系失败：" + e.getMessage());
        }
    }

    // 分页查询绑定申请记录
    @GetMapping("/list")
    public Result<IPage<BindingInfo>> getBindingList(@RequestParam int page, @RequestParam int size) {
        try {
            Page<BindingInfo> bindingInfoPage = familyElderlyBindingService.getBindingDetails(page, size);
            return Result.ok(bindingInfoPage);
        } catch (Exception e) {
            return Result.error("分页查询失败：" + e.getMessage());
        }
    }

    // 分页查询家属自己发起的绑定申请记录
    @GetMapping("/self/list")
    public Result<IPage<BindingInfo>> getSelfBindingList(@RequestParam Long familyUserId, @RequestParam int page, @RequestParam int size) {
        try {
            Page<BindingInfo> bindingInfoPage = familyElderlyBindingService.getSelfBindingDetails(familyUserId, page, size);
            return Result.ok(bindingInfoPage);
        } catch (Exception e) {
            return Result.error("分页查询失败：" + e.getMessage());
        }
    }

    // 分页查询老人自己发起的绑定申请记录
    @GetMapping("/elderly/list")
    public Result<IPage<BindingInfo>> getElderlyBindingList(@RequestParam Long elderlyUserId, @RequestParam int page, @RequestParam int size) {
        try {
            Page<BindingInfo> bindingInfoPage = familyElderlyBindingService.getElderlyBindingDetails(elderlyUserId, page, size);
            return Result.ok(bindingInfoPage);
        } catch (Exception e) {
            return Result.error("分页查询失败：" + e.getMessage());
        }
    }


    // 删除家属或老人自己的绑定申请记录
    @DeleteMapping("/self/{bindingId}")
    public Result<Void> deleteSelfBinding(@PathVariable Long bindingId, @RequestBody FamilyElderlyBinding request) {
        try {
            boolean success = familyElderlyBindingService.deleteSelfBinding(bindingId, request.getFamilyUserId());
            return success ? Result.ok() : Result.error("删除绑定失败");
        } catch (Exception e) {
            return Result.error("删除绑定失败：" + e.getMessage());
        }
    }

    // 管理员删除绑定申请记录
    @DeleteMapping("/admin/{bindingId}")
    public Result<Void> deleteBindingByAdmin(@PathVariable Long bindingId) {
        try {
            boolean success = familyElderlyBindingService.deleteBindingByAdmin(bindingId);
            return success ? Result.ok() : Result.error("删除绑定失败");
        } catch (Exception e) {
            return Result.error("删除绑定失败：" + e.getMessage());
        }
    }

    // 管理员批量删除绑定申请记录
    @DeleteMapping("/admin/batch")
    public Result<Void> batchDeleteBindingByAdmin(@RequestBody List<Long> bindingIds) {
        try {
            boolean success = familyElderlyBindingService.batchDeleteBindingByAdmin(bindingIds);
            return success ? Result.ok() : Result.error("批量删除绑定失败");
        } catch (Exception e) {
            return Result.error("批量删除绑定失败：" + e.getMessage());
        }
    }
}
